import logging
import json
import string
import random

from django.http import HttpResponse,JsonResponse
from django.shortcuts import render
from django.views import View


from . import constants
from apps.users.models import Users
from utils.captcha.captcha import captcha
from django_redis import get_redis_connection
from utils.json_fun import to_json_data
from .form import CheckImgCodeForm
from utils.res_code import Code,error_map
# from utils.yuntongxun.sms import CCP
from utils.visit_info import change_info

# 导入日志器
logger = logging.getLogger('django')

class ImageCode(View):
    """
    1 创建类视图 image
    /image_codes/<uuid:image_code_id>/
    """
    # 2 从前端获取参数 UUID


    # 5 把图片返回给前端
    def get(self,request,image_code_id):
        change_info(request)
        # 3 生成验证码文本和验证码图片
        text,image = captcha.generate_captcha()
        # 4 建立redis连接保存验证码和图片
        con_redis = get_redis_connection(alias='verify_codes')
        img_key = "img_{}".format(image_code_id).encode('utf8')
        con_redis.setex(img_key,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        logger.info("Image code: {}".format(text))

        return HttpResponse(content=image,content_type='images/jpg')


class CheckUsernameView(View):
    """
    1 写个类视图 username
    /usernames/(?P<username>\w{5,20})/
    """
    # 2 校验参数
    def get(self,request,username):
        change_info(request)
        # 3 查询数据
        count = Users.objects.filter(username=username).count()
        # 4 返回校验的结果
        data = {
            'username':username,
            # 'count':True if count else False,
            'count':count,
        }
        return to_json_data(data=data)

class CheckMobileView(View):
        """
        1 写个类视图 username
        /usernames/(?P<mobile>1[3-9]\d{9})/
        """

        # 2 校验参数
        def get(self, request, mobile):
            change_info(request)
            # 3 查询数据
            count = Users.objects.filter(mobile=mobile).count()
            # 4 返回校验的结果
            data = {
                'mobile': mobile,
                # 'count':True if count else False,
                'count': count,
            }
            return to_json_data(data=data)


class CheckSmsMobileView(View):
    """
    创建类视图 校验手机号码 图片uuid 图片验证码
    """
    # 1 前端获取数据

    # 3 生成短信验证码存入redis
    # 4 发送短语验证码
    def post(self,request):
        change_info(request)
        json_data = request.body
        if not json_data:
            return to_json_data(errno=NODATA,errmsg=error_map[Code.NODATA])
        dict_data = json.loads(json_data.decode('utf8'))
        # 2 校验数据
        check_form = CheckImgCodeForm(data=dict_data)
        if check_form.is_valid():
            mobile = check_form.cleaned_data.get("mobile")
            sms_num = ''.join([random.choice(string.digits) for _ in range(constants.SMS_CODE_NUMS)])

            # 3 生成短信验证码存入redis
            con_redis = get_redis_connection(alias='verify_codes')

            sms_flag_fmt = 'sms_flag_{}'.format(mobile).encode('utf8')
            sms_text_fmt = 'sms_text_{}'.format(mobile).encode('utf8')

            p1 = con_redis.pipeline()
            try:
                con_redis.setex(sms_flag_fmt,constants.SMS_FLAG_REDIS_EXPIRES,1)
                con_redis.setex(sms_text_fmt,constants.SMS_CODE_REDIS_EXPIRES,sms_num)
                p1.execute()
            except Exception as e:
                logger.debug("redis执行出现异常,{}".format(e))
                return to_json_data(errno=UNKOWNERR,errmsg=error_map[Code.UNKOWNERR])

            logger.info("发送验证码短信[正常][ mobile: %s sms_code: %s]" % (mobile, sms_num))
            return to_json_data(errno=Code.OK, errmsg="短信验证码发送成功")

            # 4 发送短语验证码
            # try:
            #     result = CCP().send_template_sms(mobile,
            #                                      [sms_num, constants.SMS_CODE_REDIS_EXPIRES],
            #                                      constants.SMS_CODE_TEMP_ID)
            # except Exception as e:
            #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
            #     return to_json_data(errno=Code.SMSERROR, errmsg=error_map[Code.SMSERROR])
            #
            # if result == 0:
            #     logger.info("发送验证码短信[正常][ mobile: %s sms_code: %s]" % (mobile, sms_num))
            #     return to_json_data(errno=Code.OK, errmsg="短信验证码发送成功")
            # else:
            #     logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
            #     return to_json_data(errno=Code.SMSFAIL, errmsg=error_map[Code.SMSFAIL])
        else:
            # 定义一个错误信息列表
            err_msg_list = []
            for item in check_form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
                # print(item[0].get('message'))   # for test
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)



